package com.jch.mp.manner2;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.text.SimpleDateFormat;
import java.util.Date;

public class Manner2WebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        System.out.println(dateFormat.format(new Date()) + " 收到消息: " + msg.text());
        ctx.channel().writeAndFlush(new TextWebSocketFrame("服务收到消息。"));
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println(dateFormat.format(new Date()) + " handlerAdded");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println(dateFormat.format(new Date()) + " handlerRemoved");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.err.println(dateFormat.format(new Date()) + " 异常：" + cause.getMessage());
        ctx.close();
    }
}
